<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="common.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>产品信息</title>
<script type="text/javascript">
	$(function() {

		//1.初始化Table
		var oTable = new TableInit();
		oTable.Init();
		
		//2.初始化Button的点击事件
		var oButtonInit = new ButtonInit();
		oButtonInit.Init();
		
		//下拉框动态辅助
		getCartype();
		getClassfication();
		getDistinguish();
		
		//jQuery，既阻止默认行为又停止冒泡
	    $("#ss").on('click',function(){
	    	    return false;//当然 也阻止了事件本身
	    });
		//新增修改校验
	    $(function() {
			$("#updateForm").bootstrapValidator({
					feedbackIcons : {
						valid : 'glyphicon glyphicon-ok',
						invalid : 'glyphicon glyphicon-remove',
						validating : 'glyphicon glyphicon-refresh'
					},
					fields : {
					cartype : {
						validators : {
							notEmpty : {
								message : '车种不能为空'
							},
						}
					},
					/* client : {
						validators : {
							notEmpty : {
								message : '客户不能为空'
							},
						}
					}, */
					num : {
						validators : {
							notEmpty : {
								message : '品编不能为空'
							},
						}
					},
					name : {
						validators : {
							notEmpty : {
								message : '品名不能为空'
							},
						}
					},
					/* distinguish : {
						validators : {
							notEmpty : {
								message : '产品区分不能为空'
							},
						}
					},
					classification : {
						validators : {
							notEmpty : {
								message : '产品分类不能为空'
							},
						}
					},
					size : {
						validators : {
							notEmpty : {
								message : '产品尺寸不能为空'
							},
						}
					}, */
					weight : {
						validators : {
							/* notEmpty : {
								message : '产品重量不能为空'
							}, */
							regexp : {
								regexp : /^[0-9]+([.]{1}[0-9]+){0,1}$/,
								message : '产品重量只能是整数或小数'
							}
						}
					},
					/* color : {
						validators : {
							notEmpty : {
								message : '产品颜色不能为空'
							},
						}
					}, */
					modulus : {
						validators : {
							notEmpty : {
								message : '产品模数不能为空'
							}, 
							regexp : {
								regexp : /^\d+$/,
								message : '产品模数必须为整数'
							}
						}
					},
					wweight : {
						validators : {
							/* notEmpty : {
								message : '口水重量不能为空'
							}, */
							regexp : {
								regexp : /^[0-9]+([.]{1}[0-9]+){0,1}$/,
								message : '口水重量只能是整数或小数'
							}
						}
					},
					remark4 : {
						validators : {
							/* notEmpty : {
								message : '最高库存不能为空'
							}, */
							regexp : {
								regexp : /^\d+$/,
								message : '最高库存必须为整数'
							}
						}
					},
					remark5 : {
						validators : {
							/* notEmpty : {
								message : '最低库存不能为空'
							}, */
							regexp : {
								regexp : /^\d+$/,
								message : '最低库存必须为整数'
							}
						}
					},
					remark6 : {
						validators : {
							notEmpty : {
								message : '产品周期不能为空'
							}, 
							regexp : {
								regexp : /^[0-9]+([.]{1}[0-9]+){0,1}$/,
								message : '产品周期只能是整数或小数'
							},
							callback:{
								message:'产品周期不能超过3600秒',
								callback:function(value, validator,$field){
									if(value>3600){
										return false;
									}
									return true;
								}
							}
						}
					},
					remark8 : {
						validators : {
							notEmpty : {
								message : '产品单价不能为空'
							}, 
							regexp : {
								regexp : /^[0-9]+([.]{1}[0-9]+){0,1}$/,
								message : '产品单价只能是整数或小数'
							}
						}
					}
				},
			}).on('success.form.bv',function(e) {
				$("#sv").on('click',function(){
		    	    return false;//当然 也阻止了事件本身
		   		});
				e.preventDefault();
				var url1="";
				var title = "新增";
				if("新增产品信息" == $("#bt").html()){
					url1='${pageContext.request.contextPath }/product/insert.do';
				}else if("修改产品信息" == $("#bt").html()){
					url1='${pageContext.request.contextPath }/product/update.do';
					title = "修改";
				}
				var formData = new FormData($("#updateForm")[0]);
				$.ajax({
					type : 'post',
					url : url1,
					data : formData,
					async: false,  
			        cache: false,  
			        contentType: false,  
			        processData: false,
					success : function(data) {
						if (data==1) {
							toastr.success(title+'成功');
							setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
								window.location.reload(); 
								resets();
							},1000);
						} else if (data==2) {
							toastr.warning('该信息已存在，不能重复添加');
							setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
								window.location.reload(); 
								resets();
							},1000);
						}else {
							toastr.error(title+'失败');
							setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
								window.location.reload();
								resets();
							},1000);
						}
					}
				});
			});
		});
	});
	var TableInit = function() {
		var queryUrl = '${pageContext.request.contextPath }/product/select.do';
		var oTableInit = new Object();
		//初始化Table
		oTableInit.Init = function() {
			$('#tb_departments').bootstrapTable({
				url : queryUrl, //请求后台的URL（*）
				method : 'get', //请求方式（*）
				toolbar : '#toolbar', //工具按钮用哪个容器
				striped : true, //是否显示行间隔色
				cache : true, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
				pagination : true, //是否显示分页（*）
				sortable : false, //是否启用排序
				sortOrder : "asc", //排序方式
				exportDataType : "selected",
				queryParams : oTableInit.queryParams,//传递参数（*）
				sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
				pageNumber : 1, //初始化加载第一页，默认第一页
				pageSize : 10, //每页的记录行数（*）
				pageList : [ 10,20,30 ], //可供选择的每页的行数（*）
				minimumCountColumns : 2, //最少允许的列数
				clickToSelect : true, //是否启用点击选中行
				height : 523,//865满屏  //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
				uniqueId : "ID", //每一行的唯一标识，一般为主键列
				cardView : false, //是否显示详细视图
				detailView : false, //是否显示父子表
				columns : [ {
					checkbox : true
				}, {
					field : 'pid',
				}, {
					field : 'name',
					title : '品名'
				}, {
					field : 'num',
					title : '品编'
				}, {
					field : 'cartype',
					title : '车种'
				}, {
					field : 'client',
					title : '客户'
				}, {
					field : 'distinguish',
					title : '产品区分'
				}, {
					field : 'classification',
					title : '产品分类'
				}, {
					field : 'size',
					title : '产品尺寸(mm)'
				}, {
					field : 'weight',
					title : '产品重量(g)'
				}, {
					field : 'modulus',
					title : '产品模数'
				}, {
					field : 'color',
					title : '产品颜色'
				}, {
					field : 'wweight',
					title : '水口重量(g)'
				}, {
					field : 'remark1',
					title : '模具编号'
				}, {
					field : 'remark4',
					title : '最高库存'
				}, {
					field : 'remark5',
					title : '最低库存'
				}, {
					field : 'remark7',
					title : '包装规格(个)'
				}, {
					field : 'remark6',
					title : '产品周期(s)'
				}, {
					field : 'remark8',
					title : '单价(元)'
				}]
			});
			$('#tb_departments').bootstrapTable('hideColumn', 'pid');
		};
		//得到查询的参数
		oTableInit.queryParams = function(params) {
			var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
				limit : params.limit, //页面大小
				offset : params.offset, //页码
				client : $("#client1").val(),
				cartype : $("#cartype1").val(),
				classification : $("#classification1").val(),
				distinguish : $("#distinguish1").val()
			};
			return temp;
		};
		return oTableInit;
	};
	var ButtonInit = function() {
		var oInit = new Object();
		var postdata = {};

		oInit.Init = function() {
			//初始化页面上面的按钮事件
		};

		return oInit;
	};
	// 车种下拉菜单
	function getCartype() {
		$.ajax({
			type : "post",
			url : "${pageContext.request.contextPath }/product/selectCarType.do",
			success : function(data) {
				var str = "<option value='' selected='selected'>--请选择--</option>";
				var json = eval('(' + data + ')');
				for (var i = 0; i < json.data.length; i++) {
					var cartype = json.data[i].cartype;
					str += '<option value="'+cartype+'">'
							+ json.data[i].cartype + '</option>';
				}
				$("#cartype1").append(str);
				$("#cartype1").selectpicker('refresh');
			}
		});
	}
	// 产品分类下拉菜单
	function getClassfication() {
		$.ajax({
			type : 'post',
			url : '${pageContext.request.contextPath }/product/selectClassif.do',
			success : function(data) {
				var str = "<option value='' selected='selected'>--请选择--</option>";
				var json = eval('(' + data + ')');
				for (var i = 0; i < json.data.length; i++) {
					var classification = json.data[i].classification;
					str += '<option value="'+json.data[i].classification+'">'
							+ json.data[i].classification + '</option>';
				}
				$("#classification1").append(str);
				$("#classification1").selectpicker('refresh');
			}
		});
	}
	// 产品区分下拉菜单
	function getDistinguish() {
		$.ajax({
			type : "post",
			url : '${pageContext.request.contextPath }/product/selectDis.do',
			success : function(data) {
				var str = "<option value='' selected='selected'>--请选择--</option>";
				var json = eval('(' + data + ')');
				for (var i = 0; i < json.data.length; i++) {
					var distinguish = json.data[i].distinguish;
					str += '<option value="'+distinguish+'">'
							+ json.data[i].distinguish + '</option>';
				}
				$("#distinguish1").append(str);
				$("#distinguish1").selectpicker('refresh');
			}
		});
	}
	//条件查询
	function selectByOther() {
		$("#tb_departments").bootstrapTable('refresh', {
			url : '${pageContext.request.contextPath }/product/select.do'
		});
		$("#qingkong").click(function() {
			$(".panel-body form input").each(function() {
				$(this).val('');
			});
			$(".panel-body form select").each(function() {
				$(this).val('');
			});
		});
	}
	//删除
	function doDel() {
		//必须选中一条数据
		var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
		if (checkedItems.length <= 0) {
			toastr.warning('请选择一条数据');
		} else {
			var pids = "";
			for(var i = 0;i < checkedItems.length; i++){
				if(i != checkedItems.length - 1){
					pids += checkedItems[i].pid + ",";
				}else{
					pids += checkedItems[i].pid;
				}
			}
			//询问框
			Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
					function(e) {
						if (!e) {return;}
						$.ajax({
							type : 'POST',
							url : '${pageContext.request.contextPath }/product/delete.do',
							data:'pids=' + pids,
							success : function(data) {
								if (data > 0) {
									$("#tb_departments").bootstrapTable('refresh');
									toastr.success('删除成功');
								} else {
									toastr.error('Error');
								}
							}
						});
					});
		}
	}
	//导出所有
	function exportAll() {
		Ewin.confirm({message : "确认要导出所有的数据吗？"}).on(
			function(e) {
				if (!e) {return;}
				window.location.href = "${pageContext.request.contextPath }/product/exportAll.do";
			});
	}
	//添加
	function doAdd() {
		$("#updateForm")[0].reset();//打开模态框前进行重置
		$("#bt").html("新增产品信息");
		$("#updateModal").modal(open);
		
	}
	//修改
	function doUpdate() {
		//必须选中一条数据
		var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
		if (checkedItems.length == 1) {
			$("#bt").html("修改产品信息");
			$("#updateModal").modal("show");
			$.ajax({
				type:"post",
				url: '${pageContext.request.contextPath }/product/selectByID.do',
				data:{pid:checkedItems[0].pid},
				success:function(data){
					var json = eval('('+data+')');
					$("#pid").val(json.rows[0].pid);
					$("#cartype").val(json.rows[0].cartype);
					$("#client").val(json.rows[0].client);
					$("#num").val(json.rows[0].num);
					$("#name").val(json.rows[0].name);
					$("#distinguish").val(json.rows[0].distinguish);
					$("#classification").val(json.rows[0].classification);
					$("#size").val(json.rows[0].size);
					$("#weight").val(json.rows[0].weight);
					$("#color").val(json.rows[0].color);
					$("#modulus").val(json.rows[0].modulus);
					$("#wweight").val(json.rows[0].wweight);
					$("#remark1").val(json.rows[0].remark1);
					$("#remark3").val(json.rows[0].remark3);
					$("#remark4").val(json.rows[0].remark4);
					$("#remark5").val(json.rows[0].remark5);
					$("#remark7").val(json.rows[0].remark7);
					$("#remark6").val(json.rows[0].remark6);
					$("#remark8").val(json.rows[0].remark8);
				}
			});
		} else {
			toastr.warning('请只选择一条数据');
		}
	}
	//关闭添加表单时清空数据
	function resets() {
		$('#updateForm').data('bootstrapValidator').resetForm(true);
	}
	function douploadModal() {
		$('#uploadModal').modal(open);
		//清空表单
		document.getElementById("importForm").reset();
	}
	function uploadBtn() {
		 var fileName = $("#fileInput").val();
		 if (fileName.length > 0) {
		     var formData = new FormData($("#importForm")[0]);  
		     $.ajax({ 
		          url: '${pageContext.request.contextPath}/product/uplodeFile.do' ,  
		          data: formData,
		          type:'post',
		          async: false,  
		          cache: false,
		          contentType: false,  
		          processData: false,
		          success: function (data) { 
		        	  if (data == 1) {
		        		  toastr.success('文件导入成功（重复数据已过虑）！');
		        		  setTimeout(function(){
								window.location.reload(); 
							},1000);
		        	  }else{
		        		  toastr.warning('文件格式异常，文件导入失败！');  
		        	  }
		          },
		          error: function (data) {
		        	  toastr.error("文件格式异常，导入的数据不符合导入条件");  
		          }
		     }); 
		 }else{
			 toastr.warning('上传文件为空，请选择要导入的文件！');  
		}
	}
	//导出数据模板
	function doExportFile() {
		Ewin.confirm({message : "确认要导出数据模板吗？"}).on(
			function(e) {
				if (!e) {return;}
			window.location.href="${pageContext.request.contextPath}/product/doExportFile.do"; 
			$('#uploadModal').modal('hide'); 
		});
	}
	//提示框的位置设置为中上
	toastr.options.positionClass = 'toast-top-center';
</script>
</head>
<body>
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content">
      			<div class="modal-header">
        			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
        				<span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span style="font-size:13px">excel导入</span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="importForm" class="form-horizontal">
	        			<div class="form-group">
							<label  class="col-sm-3 control-label"></label>
							<div class="col-sm-7"> 
		           				 <button id="btn_delete" type="button" class="btn btn-default" 
		           				 	onclick="doExportFile()">
					                <span class="glyphicon glyphicon-export" aria-hidden="true">
					                </span>导出数据模板
					            </button>
	          				 </div>
	          			</div>
	          			<div class="form-group">
				            <label class="col-sm-5 control-label">excel文件:</label>
				            <div class="col-sm-5"> 
					            <input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
	          				</div>
	          			</div>
	        			<div class="form-group"> 
				   			<div class="col-sm-3 col-sm-offset-7">  
						        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						        <button type="submit"  name="submit"  class="btn btn-primary" id="ss" 
						        	onclick="uploadBtn()">导入</button>
			      			</div>
			      		</div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>
	<div class="panel-body" style="padding-bottom: 0px;">
		<div class="panel panel-default">
			<div class="panel-heading">查询条件</div>
			<div class="panel-body">
				<form id="formSearch" class="form-horizontal">
					<div class="form-group" style="margin-top: 15px">
						<label class="control-label col-sm-1" for="client1">客户</label>
						<div class="col-sm-3">
							<input type="text" class="form-control" id="client1">
						</div>
						<label class="control-label col-sm-1" for="cartype1">车种</label>
						<div class="col-sm-3">
							<select id="cartype1" class="selectpicker show-tick form-control">
							</select>
						</div>
						<br> <br> <br> <label
							class="control-label col-sm-1" for="classification1">产品分类</label>
						<div class="col-sm-3">
							<select id="classification1"
								class="selectpicker show-tick form-control">
							</select>
						</div>
						<label class="control-label col-sm-1" for="distinguish1">产品区分</label>
						<div class="col-sm-3">
							<select id="distinguish1"
								class="selectpicker show-tick form-control">
							</select>
						</div>
						<div class="col-sm-4" style="margin-top: -30px;">
							<button type="button" style="margin-left: 20%;"
								id="btn_query" class="btn btn-primary" onclick="selectByOther()"
								data-query-params="queryParams" data-query-params-type="limit">查询</button>
							<button id="qingkong" hidden="hidden">清空筛选</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div id="toolbar" class="btn-group">
			<button type="button" class="btn btn-default" onclick="doAdd()">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
			</button>
			<button type="button" class="btn btn-default" onclick="doUpdate()">
				<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
			</button>
			<button onclick="doDel()" type="button" class="btn btn-default">
				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
			</button>
			<button id="btn_import" type="button" class="btn btn-default" onclick="douploadModal()">
           		<span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>导入
        	</button>
			<button type="button" class="btn btn-default" onclick="exportAll()">
				<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出所有
			</button>
			<button type="button" class="btn btn-default" style="display: none;">
				<span class="glyphicon glyphicon-cancel" aria-hidden="true"></span>隐藏
			</button>
		</div>
		<table id="tb_departments"></table>
	</div>
	<!-- 新增修改 -->
	<div class="modal fade bs-example-modal-lg" id="updateModal" tabindex="-1" role="dialog" 
		aria-labelledby="updateModal" aria-hidden="true" >
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="updateModalLabel">
						<span id="bt" style="font-size:13px"></span>
					</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="updateForm" method="post">
					<input type="hidden" id="pid" name="pid"/>
						<div class="form-group">
							<label for="cartype" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">车种:</label>
							<div class="col-sm-4">
								<input type="text" id="cartype" name="cartype" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
							<label for="client" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">客户:</label>
							<div class="col-sm-4">
								<input type="text" id="client" name="client" class="form-control">
							</div>
						</div>
						<div class="form-group">
							<label for="weight" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">产品重量:</label>
							<div class="col-sm-4">
								<input type="text" id="weight" name="weight" class="form-control">
							</div>
							<div style="width: 8px; float: left;margin-top: 5px;margin-left: -10px;">
								<span>g</span>
							</div>
							<label for="num" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">品编:</label>
							<div class="col-sm-4">
								<input type="text" id="num" name="num" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="name" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">品名:</label>
							<div class="col-sm-4">
								<input type="text" id="name" name="name" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
							<label for="distinguish" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">产品区分:</label>
							<div class="col-sm-4">
								<input type="text" id="distinguish" name="distinguish" class="form-control">
							</div>
						</div>
						<div class="form-group">
							<label for="classification" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">产品分类:</label>
							<div class="col-sm-4">
								<input type="text" id="classification" name="classification" 
									class="form-control">
							</div>
							<label for="size" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">产品尺寸:</label>
							<div class="col-sm-4">
								<input type="text" id="size" name="size" class="form-control">
							</div>
						</div>
						<div class="form-group">
							<label for="color" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">产品颜色:</label>
							<div class="col-sm-4">
								<input type="text" id="color" name="color" class="form-control">
							</div>
							<label for="modulus" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">产品模数:</label>
							<div class="col-sm-4">
								<input type="text" id="modulus" name="modulus" class="form-control">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="wweight" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">水口重量:</label>
							<div class="col-sm-4">
								<input type="text" name="wweight" id="wweight" class="form-control">
							</div>
							<div style="width: 8px; float: left;margin-top: 5px;margin-left: -10px;">
								<span>g</span>
							</div>
							<label for="remark1" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">模具编号:</label>
							<div class="col-sm-4">
								<input type="text" id="remark1" name="remark1" class="form-control">
							</div>
						</div>
						<div class="form-group">
							<label for="remark4" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">最高库存:</label>
							<div class="col-sm-4">
								<input type="text" id="remark4" name="remark4" class="form-control">
							</div>
							<label for="remark5" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">最低库存:</label>
							<div class="col-sm-4">
								<input type="text" id="remark5" name="remark5" class="form-control">
							</div>
						</div>
						<div class="form-group">
							<label for="remark7" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">包装规格:</label>
							<div class="col-sm-4">
								<input type="text" id="remark7" name="remark7" class="form-control">
							</div>
							<label for="remark6" class="col-sm-2 control-label" style="width: 11%;
								margin-left: 35px;">产品周期:</label>
							<div class="col-sm-4">
								<input type="text" id="remark6" name="remark6" class="form-control">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="remark8" class="col-sm-2 control-label" style="width: 11%;
								margin-left:30px;">产品单价</label>
							<div class="col-sm-4">
								<input type="text" id="remark8" name="remark8" class="form-control">
								<span class="xing"></span>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" 
								onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary" id="sv">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>